<template>
    <div class="layout-main" style="min-height: 800px;">
        <el-row>
            <el-col :span="4">
                <div>&nbsp;&nbsp;&nbsp;&nbsp;</div>
                <div style="z-index:99999;position: fixed;top: 100px;height: calc(100% - 120px);overflow: scroll;">
                    <div>
                        打印机状态：<el-button size="small" @click="initPrint">
                            {{socket&&socket.readyState==1?'已连接':"点击连接"}}
                        </el-button>
                    </div>
                    <div>
                        送货单号：
                        <el-input v-model="waybillOrder" @keyup.enter.native="toGo" placeholder="送货单号" style="width: 240px;margin-bottom: 10px;" />
                    </div>
                    <el-steps direction="vertical">
                        <el-step @click.native="scrollToAnchor('dt'+item.id)" v-for="(item,ind) in orderItems" :id="'step'+item.id">
                            <span v-if="item.state==1" slot="title" class="state-success">
                                {{item.productCode}}
                            </span>
                            <template v-else>
                                <span v-if="ind==currentItemIndex" class="state-error" slot="title">
                                    {{item.productCode}}
                                </span>
                                <span v-else slot="title">
                                    {{item.productCode}}
                                </span>
                            </template>
                        </el-step>
                    </el-steps>
                </div>
            </el-col>
            <el-col :span="12">
                <el-divider content-position="left">订单明细</el-divider>
                <div v-for="(item,ind) in orderItems" style="margin-bottom: 20px;" :id="'dt'+item.id">
                    <el-card class="box-card" :style="{borderColor:(ind==currentItemIndex)?'#ff0000':''}">
                        <div slot="header" class="clearfix">
                            <div>
                                <span style="margin-left: 20px">商品编码：{{item.productCode}}</span>
                                ，
                                外箱数量：{{item.outerPackageCount}}，已复核数量：{{item.signOuterCount}}
                            </div>
                        </div>
                        <el-card class="box-card" v-for="(outer,outerIndex) in item.outerItems" :style="{borderColor:(outerIndex==currentOuterIndex && ind==currentItemIndex)?'#ff0000':''}">
                            <div slot="header" class="clearfix">
                                外箱：{{outer.outerPackageSn}},总数量：{{outer.outerIncludeQty}},大包数量：{{outer.bigPackageCount}}，已复核数量：{{outer.signBigCount}}
                            </div>
                            <el-card class="box-card" v-for="(bigitem,bigIndex) in outer.bigItems" :style="{borderColor:(outerIndex==currentOuterIndex && ind==currentItemIndex && bigIndex==currentBigIndex)?'#ff0000':''}" :id="'dt'+bigitem.bigPackageSn">
                                <div slot="header" class="clearfix">
                                    大包：{{bigitem.bigPackageSn}},总数量：{{bigitem.bigIncludeQty}},小包数量：{{bigitem.smallPackageCount}}，已复核数量：{{bigitem.signCount}}
                                </div>
                                <el-table size="small" :data="bigitem.detailItems" border style="width: 100%">
                                    <el-table-column align="left" width="340" prop="projectNo" label="客户规格描述">
                                        <template slot-scope="scope">
                                            <div>{{scope.row.productName}}</div>
                                            <div>{{scope.row.productScale}}</div>
                                            <div> {{scope.row.smallBarcode}}</div>
                                            <div> {{scope.row.bigPackageSn}}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="left" width="120" prop="projectNo" label="客户单号">
                                        <template slot-scope="scope">
                                            {{scope.row.poErpNo}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="left" width="120" prop="projectNo" label="生产日期">
                                        <template slot-scope="scope">
                                            {{scope.row[orderDetail['createTimeField']]}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="left" width="120" prop="projectNo" label="数量">
                                        <template slot-scope="scope">
                                            {{scope.row.includeQty}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" width="80" fixed="left" prop="projectNo" label="状态">
                                        <template slot-scope="scope">
                                            <span v-if="scope.row.state==1" class="state-success-full">成功</span>
                                            <span v-else class="state--full">待复核</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-card>
                        </el-card>
                    </el-card>
                </div>
            </el-col>
            <el-col :span="8">
                <div>&nbsp;</div>
                <div style="position:fixed;top: 100px;width: 100%;">
                    <el-divider content-position="left">扫码复核</el-divider>
                    <el-form style="margin-top: 20px" inline label-position="right" label-width="120px" @submit.native.prevent="()=>{}">
                        <el-form-item label="标签条码">
                            <el-input ref="waybillOrder" v-model="boxOrder" styl @keyup.enter.native="toFuhe" placeholder="标签条码" style="width:500px" />
                        </el-form-item>
                    </el-form>
                    <div style="margin-bottom:10px">
                        <el-checkbox style="margin-left:10px;" v-model="showOk" @change="setMouse">固定鼠标</el-checkbox>
                        <el-button size="small" style="margin-left:10px" type="danger" @click="clearForm">清空重新复核</el-button>
                    </div>
                    <div style="padding: 20px;">
                        <ul>
                            <li v-for="(log,ind) in logs" :key="ind" class="log-list">
                                <span v-if="log.state==1" style="line-height: 20px;font-size: 16px;" class="state-success">【{{ind+1}}】、{{log.info}}</span>
                                <span v-if="log.state==0" style="line-height: 20px;font-size: 16px;" class="state-primary">【{{ind+1}}】、{{log.info}}</span>
                                <span v-if="log.state==-1" style="line-height: 20px;font-size: 16px;" class="state-error">【{{ind+1}}】、{{log.info}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import iNotify from '@/assets/iNotify'
import api from "@/api/api"
import { getRand } from '@/utils/random'
export default {
    name: "Outgo",
    data() {
        return {
            socket: null,
            waybillOrder: "22240415YVCF",
            fouceTimer: null,
            showOk: false,
            orderDetail: {},
            boxOrder: "SM-202404070074#01.ER0.000RJ04021A#0402WGJ0000TCE#10000#20240412#20240416",
            orderItems: [],
            logs: [],
            checkDto: {

            },
            currentItemIndex: -1,
            currentBigIndex: -1,
            currentOuterIndex: -1,
            printLogs: []
        }
    },
    mounted: function() {
        this.setMouse(false);
        this.initPrint();

    },
    beforeRouteLeave(to, from, next) {
        const answer = window.confirm("确定离开这个页面");
        if (answer) {
            next();
        } else {
            next(false);
        }
    },
    methods: {

        scrollToAnchor: function(id) {

            document.getElementById(id).scrollIntoView()
        },
        toFuhe() {
            var me = this;
            if (!me.boxOrder)
                return;
            // if (!me.socket || me.socket.readyState != 1) {
            //     me.errorMessage("打印机未连接上")
            //     return;
            // }
            //循环列表 客户订单号#客户料号#原厂料号#数量#生产日期#批次

            var strs = me.boxOrder.split("#");
            var khddh = strs[0];
            var khlh = strs[1];
            var qty = parseInt(strs[3]);
            var scrq = strs[4];
            var scpc = strs[5];

            var ok = false;
            var itemIndex = 0;
            var outerIndex = 0;
            var bigIndex = 0;
            var subIndex = 0;

            for (var i = 0; i < me.orderItems.length; i++) {
                var item = me.orderItems[i];
                for (var oIndex = 0; oIndex < item.outerItems.length; oIndex++) {
                    var outerItem = item.outerItems[oIndex];
                    for (var bIndex = 0; bIndex < outerItem.bigItems.length; bIndex++) {
                        var bigItem = outerItem.bigItems[bIndex];
                        for (var sIndex = 0; sIndex < bigItem.detailItems.length; sIndex++) {

                            var detailItem = bigItem.detailItems[sIndex];
                             
                         
                            if (detailItem.productCode != khlh) {
                                continue;
                            }
                            if (detailItem.state != 0) {
                                continue;
                            }

                            if (me.orderDetail.sc == 1) //需要验证生产日期
                            {
                                if (detailItem[me.orderDetail['createTimeField']] != scrq) {
                                    continue;
                                }
                            }
                            if (me.orderDetail.dc == 1) //需要验证批次
                            {
                                if (detailItem['poErpNo'] != scpc) {
                                    continue;
                                }
                            }
                            if (me.orderDetail.pn == 1) //客户单号
                            {
                                if (detailItem[me.orderDetail['batchField']] != khddh) {
                                    continue;
                                }
                            }
                            ok = true;
                            subIndex = sIndex;
                            // me.checkDto['itemDetailId'] = detailItem.id;
                            break;
                        } //最内层
                        if (ok) {
                            bigIndex = bIndex;
                            // me.checkDto['bigId'] = bigItem.id;
                            break;
                        }
                    } //大包
                    if (ok) {
                        outerIndex = oIndex;
                        // me.checkDto['outerId'] = outerItem.id;
                        break;
                    }
                } //外包
                if (ok) {

                    itemIndex = i;
                    // me.checkDto['itemId'] = item.id;
                    break;
                }
            } //最外层
            if (ok) {

                me.currentItemIndex = itemIndex;
                if (me.currentOuterIndex == -1) {
                    me.currentOuterIndex = outerIndex;
                }
                if (me.currentBigIndex == -1) {
                    me.currentBigIndex = bigIndex;
                }
                if (me.currentBigIndex != bigIndex || me.currentOuterIndex != outerIndex) {
                    me.logs.unshift({ info: me.boxOrder + "对不上了", state: -1 });
                    iNotify.player("signError")
                    return;
                }
                var tpItems = me.orderItems[itemIndex]['outerItems'][outerIndex]['bigItems'][bigIndex];
                if (tpItems.smallPackageCount == tpItems.signCount) {
                    //重复了
                    iNotify.player("signDouble")
                    me.logs.unshift({ info: me.boxOrder + "重复了", state: 0 });
                    return;
                }
                // me.checkDto['currentOuterIndex'] = me.currentOuterIndex;
                // me.checkDto['currentBigIndex'] = me.currentBigIndex;
                // me.checkDto['currentIndex'] = me.itemIndex;
                // me.checkDto['orderId'] = me.orderDetail.id;


                me.logs.unshift({ info: me.boxOrder + "复核成功！", state: 1 });
                me.$set(tpItems, "signCount", tpItems.signCount + 1);
                me.$set(tpItems.detailItems[subIndex], "state", 1);
                iNotify.player("signOk");
                // iNotify.player("printsmall")
                setTimeout(function() { iNotify.player("printSmall") }, 1500);
                me.logs.unshift({ info: "打印小箱标签", state: 1 });
                // me.printSend(me.orderDetail.smallPackage, me.orderDetail.smallFields, me.tpItems.detailItems[subIndex]); //打印小包


                if (tpItems.smallPackageCount == tpItems.signCount) { //打印大箱子
                    me.$set(tpItems, "state", 1);
                    me.$set(me.orderItems[itemIndex]['outerItems'][outerIndex], "signBigCount", me.orderItems[itemIndex]['outerItems'][outerIndex].signBigCount + 1);

                    if (tpItems['detailItems'][subIndex]['packLevel'] > 1) {
                        setTimeout(function() { iNotify.player("printBig") }, 4000);
                        me.logs.unshift({ info: "打印大箱标签", state: 1 });
                    }
                    me.currentBigIndex = -1;

                }
                if (me.orderItems[itemIndex]['outerItems'][outerIndex].bigPackageCount == me.orderItems[itemIndex]['outerItems'][outerIndex].signBigCount) { //打印外箱

                    me.$set(me.orderItems[itemIndex]['outerItems'][outerIndex], "state", 1);
                    me.$set(me.orderItems[itemIndex], "signOuterCount", me.orderItems[itemIndex].signOuterCount + 1);
                    if (tpItems['packLevel'] > 2) {
                        setTimeout(function() { iNotify.player("printOut") }, 6000);
                        me.logs.unshift({ info: "打印外箱标签", state: 1 });
                    }
                    me.currentOuterIndex = -1;
                }

                if (me.orderItems[itemIndex].outerPackageCount == me.orderItems[itemIndex].signOuterCount) {
                    me.$set(me.orderItems[itemIndex], "state", 1);
                }
                me.scrollToAnchor("dt" + me.orderItems[itemIndex]['outerItems'][outerIndex]['bigItems'][bigIndex].bigPackageSn);
                me.scrollToAnchor("step" + me.orderItems[itemIndex].id);
                //排序
                // me.toSort();
                // me.toOk();
                me.toCallback();


            } else { //失败
                me.logs.unshift({ info: me.boxOrder + "对不上了", state: -1 });
                iNotify.player("signError")
            }
        },
        toCallback() {
            var me = this;
            me.showLoading();
            me.$http.post("/sys/saleorder/callBack.action", me.checkDto).then(response => {
                me.hideLoading();
                if (response.status == 0) {


                } else {
                    me.errorMessage(response.info);
                }

            }, response => {
                me.hideLoading();
            });

        },
        toSort() {
            this.orderItems.sort((max, min) => {
                var a = 0;
                var b = 0;
                if (max.signCount > 0) {
                    a = max.signCount == max.smallPackageCount ? -1 : 1;
                }
                if (min.signCount > 0) {
                    b = min.signCount == min.smallPackageCount ? -1 : 1;
                }
                return b - a;

            });
        },
        toOk() {
            var me = this;
            for (var i = 0; i < me.orderItems.length; i++) {
                var item = me.orderItems[i];
                if (item.state != 1) {
                    return;
                }
            }
            this.$confirm('已打印完毕是否提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

            }).catch(() => {

            });
        },
        toGo() { //获取列表
            var me = this;
            if (!me.waybillOrder) {
                return;
            }

            me.showLoading();
            me.$http.post("/sys/saleorder/getItems.action", { id: me.waybillOrder }).then(response => {
                me.hideLoading();
                if (response.status == 0) {
                    response.obj.items.forEach(item => {
                        // me.$set(item, "signOuterCount", 0);
                        // me.$set(item, "state", 0);
                        item.outerItems.forEach(outerItem => {
                            // me.$set(outerItem, "signBigCount", 0);
                            me.$set(outerItem, "state", 0);
                            outerItem.bigItems.forEach(bigItem => {
                                // me.$set(bigItem, "signCount", 0);
                                // me.$set(bigItem, "state", 0);
                                bigItem.detailItems.forEach(subItem => {
                                    // me.$set(subItem, "state", 0);

                                });
                            });
                        });
                    });
                    me.orderItems = response.obj.items;
                    me.orderDetail = response.obj;

                } else {
                    me.errorMessage(response.info);
                }

            }, response => {
                me.hideLoading();
            });

        },
        setMouse(val) {
            var me = this;
            if (val) {
                me.fouceTimer = setInterval(function() {
                    me.$refs['waybillOrder'].focus();
                }, 500);
            } else {
                if (this.fouceTimer) {
                    window.clearInterval(this.fouceTimer)
                }
            }
        },

        clearForm: function() {
            this.orderItems = [];
            this.logs = [];
        },

        doConnect: function(callback) {
            let serviceUrl = "ws://localhost:30002/echo";
            var me = this;
            me.socket = new WebSocket(serviceUrl);

            // 监听消息
            me.socket.onmessage = function(event) {
                console.log('Client received a message', event);

                let data = JSON.parse(event.data);

                if (data.cmd == "opened") {

                    console.log("连接到打印服务器了")

                } else if (data.cmd == "print") {

                    if (data.msg == "成功") {


                    } else {

                    }
                }

            };

            me.socket.onopen = function(event) {
                if (callback != null) {
                    callback();
                }

            }

            me.socket.onerror = function(error) {
                console.log("Failed to connect CN print at " + serviceUrl, error);

            }

            // 监听Socket的关闭
            me.socket.onclose = function(event) {
                console.log('Client notified socket has closed', event);
                me.$confirm('打印机未连接上,无法打印', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                }).catch(() => {

                });
            };
        },
        initPrint: function() {
            if (!this.socket || typeof this.socket == "undefined" || this.socket.readyState == WebSocket.CLOSED) {
                this.doConnect(this.initPrint);
                return;
            }
            if (this.socket && typeof this.socket != "undefined" && this.socket.readyState == 1) {
                // this.printName = localStorage.getItem("defaultPrinter");
                // this.getPrinters();
                this.successMessage("连接到打印服务器了")
            } else {
                this.printName = "";
            }
        },
        printSend: function(filePath, strfields, data) {
            // debugger;

            let time = new Date().getTime() + getRand();
            let realData = {};
            // debugger;
            let fields = strfields.split(",");
            for (var k in data) {
                // if(fields.indexOf(k)!=-1)
                // {
                //     realData[k]=data[k];
                if (!data[k] || k == "state") {
                    continue;
                }
                if (!realData[k]) {
                    realData[k] = data[k];
                }
                if (k == 'dynamicData') {
                    for (var kd in data['dynamicData']) {
                        if (realData.hasOwnProperty(kd)) //已经有了就覆盖
                        {
                            realData[kd] = data['dynamicData'][kd];
                        } else {
                            if (fields.indexOf(kd) != -1) {
                                realData[kd] = data['dynamicData'][kd];
                            }
                        }
                    }
                }
            }
            let printData = {
                "cmd": "print",
                "version": "1.0",
                "filePath": filePath,
                "requestId": time,
                "data": realData
            }
            // debugger;
            this.logs.push({ state: 1, info: JSON.stringify(printData) });
            this.socket.send(JSON.stringify(printData));

        }
    }
}
</script>
<style scoped>
.log-list {
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px dotted #cecece;
}

.log-list span {
    display: inline-block;
    /* 或者 block */
    white-space: normal;
    /* 使文本正常换行 */
    word-break: break-all;
    /* 如果需要在任意字符间断开单词 */
}
</style>